/* eslint-disable react-hooks/exhaustive-deps */
//获取ajax 获取用户信息

import { useState ,useEffect} from "react"
import { useDispatch } from "react-redux"
import { useRequest } from "ahooks"
import useGetUserInfo from "./useGetUserInfo"
import { getUserInfoService } from "../services/user"
import { loginReducer } from "../store/userReducer"

function useLoadUserData(){
    const dispatch=useDispatch()
    const [waitingUserData,setWaitingUserData]=useState(true)
    //ajax 加载用户信息
    const {run}=useRequest(getUserInfoService,{
        manual:true,
        onSuccess(result){
            const {username,nickname}=result
            // 存储到redux store 中
            dispatch(loginReducer({username,nickname}))
        },
        onFinally(){
            setWaitingUserData(false)
        }
    })
    //判断当前 redux store 是否已经存在用户信息
    const {username} =useGetUserInfo() // redux store
    useEffect(()=>{
        if(username){
            setWaitingUserData(false)
            return 
        }
        run() //如果redux 中没有用户信息，则加载
    },[username])

    return {waitingUserData}
}
export default useLoadUserData
